# 认证类


from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication
from itsdangerous import TimedJSONWebSignatureSerializer as Jwt
from django.conf import settings


class ExpiringTokenAuthentication(BaseAuthentication):
    def authenticate(self, request):
        #从头部获取token

        token = request.META.get('HTTP_TOKEN')

        if not token:
            token = request.META.get('HTTP_AUTHORIZATION').split(' ')[-1]

        if not token:
            raise exceptions.AuthenticationFailed('认证失败,token不能为空')
        #token解码，生成对应的用户信息
        serializer = Jwt(settings.SECRET_KEY,  settings.TOKEN_OUT_TIME)

        try:
            user = serializer.loads(token)
            return (user,'')
        except Exception as ex:
            print("exception",ex)
            raise exceptions.AuthenticationFailed('认证失败,token格式不正确')

        # TODO: 验证 token

       # return self().authenticate_credentials(token)

    def authenticate_credentials(self, key):
        # TODO 验证用户
        user = {}
        # 返回用户信息
        return user, key

    def authenticate_header(self, request):
        pass
